package com.qk.management.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.vo.portal.PortalVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class MpAspect {

    @Autowired
    private StringRedisTemplate redisClient;

    private static final String CACHE_PORTAL_KEY_PREFIX = "qk:portal:";


    @Pointcut("execution(* com.qk.management.service.impl.ReportOverviewServiceImpl.*(..))")
    public void pointcut() {
    }


    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        String redisKey = CACHE_PORTAL_KEY_PREFIX + "reportOverview";
        String jsonStr = null;

        try {
            jsonStr = redisClient.opsForValue().get(redisKey);
            if (ObjectUtil.isNotEmpty(jsonStr)){
                return JSONUtil.toBean(jsonStr, PortalVO.class);
            }
        } catch (Exception e) {
            log.error("redis缓存获取失败：{}", e.getMessage());
        }

        Object proceed = pjp.proceed();

        try {
            redisClient.opsForValue().set(redisKey, JSONUtil.toJsonStr(proceed));
        } catch (Exception e) {
            log.error("redis缓存写入失败：{}", e.getMessage());
        }

        return proceed;
    }
}
